<script lang="ts" setup>
import { Notification, Modal } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue/es/form'
import type { TableRowSelection } from '@arco-design/web-vue'
import { TitleMap, BasePagination } from '@/config/constants'
import TableToolBar from '@/components/TableToolBar/index.vue'
import MyTransition from '@/components/MyTransition/index.vue'
import Edit from './edit.vue'
import { set } from '@vueuse/core'
import request from '@/utils/request'
import { debounce, cloneDeep } from 'lodash'

const { page, limit } = BasePagination
const data = reactive<any>({
  modelForm: {
    status: 1,
    ord: '1',
  },
  // 查询对象
  queryParams: {
    username: '',
    page,
    limit,
  },
  // 列表数据
  tableData: [],
  pagination: {
    ...BasePagination,
  },
})
const showSearch = ref(true)
const tableLoading = ref(false)
const editVisible = ref(false)
const delDisabled = ref(false)
const dialogStatus = ref('create')
const selectedKeys = ref<any>([])
const rowSelection: TableRowSelection = {
  type: 'checkbox',
  showCheckedAll: true,
}
const formQueryRef = ref<FormInstance>()
const setEditVisible = () => {
  set(editVisible, false)
}
const onSearch = debounce(() => {
  getList()
}, 500)

const onReset = debounce(() => {
  formQueryRef.value?.resetFields()
  getList()
}, 500)

const onAdd = () => {
  set(editVisible, true)
  set(dialogStatus, 'create')
}

// 获取列表
const getList = () => {
  set(tableLoading, true)

  request({
    url: '/user',
    params: data.queryParams,
  })
    .then((res) => {
      Array.isArray(res.rows) && (data.tableData = res?.rows)

      const page = data.queryParams.page
      const total = res.page.total

      Object.assign(data.pagination, { page, total })

      setTimeout(() => {
        set(tableLoading, false)
      }, 80)
    })
    .catch((e) => {
      console.log(e)
    })
    .finally(() => {
      set(tableLoading, false)
    })
}

getList()

const onPageChange = (page: number) => {
  data.queryParams.page = page
  getList()
}

// 处理编辑
const handleEdit = (row: any) => {
  set(editVisible, true)
  set(dialogStatus, 'update')

  delete row.password

  row.isTop = !!row.isTop
  // row.status = !!row.status

  Object.assign(data.modelForm, row)
}

// 处理文章状态
const handleStatusChange = debounce((v, row) => {
  const text = row.status ? '停止' : '激活'

  Modal.confirm({
    title: '温馨提示',
    content: '确认要 『 ' + text + ' 』 该用户吗？',
    okButtonProps: {
      status: 'danger',
    },
    onOk: () => {
      onStatusChange(row)
    },
  })
}, 500)

const onStatusChange = (row: any) => {
  Object.assign(data.modelForm, cloneDeep(row))
  // bool类型转换为int存储
  data.modelForm.status = +!row.status

  updateData(data.modelForm)
}

// 新增数据
const createData = (data: any) => {
  request({
    method: 'post',
    url: '/user',
    data,
  }).then((res) => {
    res && handleSuccess()
  })
}

// 修改数据
const updateData = (data: any) => {
  request({
    method: 'patch',
    url: `/user/${data.id}`,
    data,
  }).then((res) => {
    set(dialogStatus, 'update')
    res && handleSuccess()
  })
}

// 批量删除
const onRemove = () => {
  if (!selectedKeys.value.length) {
    Notification.error('至少选择一个')
    return
  }

  Modal.confirm({
    draggable: true,
    title: '温馨提示',
    content: '你确定要删除选中项吗?',
    onOk() {
      onDelete(selectedKeys.value.join(','))
    },
  })
}

// 处理删除
const handleDelete = (data: any) => {
  onDelete(data?.id)
}

// 删除
const onDelete = (id: string) => {
  request({
    method: 'delete',
    url: `/user/${id}`,
  }).then((res) => {
    set(dialogStatus, 'delete')
    res && handleSuccess()
  })
}

// 处理成功
const handleSuccess = () => {
  refreshData()
}

// 刷新数据
const refreshData = () => {
  getList()
  Notification.info({
    content: `${TitleMap[dialogStatus.value as keyof typeof TitleMap] || '操作'}成功`,
    duration: 3000,
  })
}

// 监听批量删除按钮
watch(
  () => selectedKeys.value.length,
  (value) => {
    delDisabled.value = !value
  },
  { immediate: true }
)
</script>
<template>
  <a-card class="app-blog-list">
    <my-transition>
      <div class="app-card-header" v-show="showSearch">
        <a-form ref="formQueryRef" :model="data.queryParams" layout="inline" @submit="onSearch">
          <a-form-item field="username" label="名称">
            <a-input v-model.trim="data.queryParams.username" :style="{ width: '320px' }" allow-clear placeholder="请输入名称" @keyup.enter="onSearch" />
          </a-form-item>
          <a-form-item>
            <a-space :size="10">
              <a-button type="primary" html-type="submit">
                <template #icon>
                  <icon-search />
                </template>
                <template #default>查询</template>
              </a-button>
              <a-button @click="onReset">
                <template #icon>
                  <icon-refresh />
                </template>
                <template #default>重置</template>
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>
    </my-transition>
    <div class="app-card-body">
      <div class="app-table-action">
        <div class="app-table-btn">
          <a-space :size="10">
            <a-button type="primary" @click="onAdd">
              <template #icon>
                <icon-plus />
              </template>
              <template #default>新增</template>
            </a-button>
            <a-button type="outline" status="danger" :disabled="delDisabled" @click="onRemove">
              <template #icon>
                <icon-delete />
              </template>
              <template #default>删除</template>
            </a-button>
          </a-space>
        </div>
        <div class="app-table-action-right">
          <table-tool-bar v-model:show-search.sync="showSearch" @query-table="getList" />
        </div>
      </div>
      <!-- /table-action -->
      <div class="app-table-container">
        <a-table stripe :data="data.tableData" row-key="id" :pagination="data.pagination" @page-change="onPageChange" :loading="tableLoading" :row-selection="rowSelection" v-model:selectedKeys="selectedKeys">
          <template #columns>
            <a-table-column title="id" data-index="id" />
            <a-table-column title="用户名" data-index="username">
              <template #cell="{ record }">
                <a-link :href="`/blog/${record.id}`" target="_blank" icon>{{ record.username }}</a-link>
              </template>
            </a-table-column>
            <a-table-column title="昵称" data-index="nickName" />
            <a-table-column title="手机号码" data-index="phone" />
            <a-table-column title="备注" data-index="remark" />
            <a-table-column title="状态" data-index="status">
              <template #cell="{ record }">
                <a-switch :default-checked="record.status == 1" @change="(v: any) => handleStatusChange(v, record)" checked-color="#13ce66" unchecked-color="#DCDFE6" />
              </template>
            </a-table-column>
            <a-table-column title="更新时间" data-index="updateTime" />
            <a-table-column title="操作" :width="80">
              <template #cell="{ record }">
                <a-space>
                  <a-button type="text" @click="handleEdit(record)">
                    <template #icon>
                      <icon-edit />
                    </template>
                    <template #default>修改</template>
                  </a-button>
                  <a-button type="text" status="danger" @click="handleDelete(record)">
                    <template #icon>
                      <icon-delete />
                    </template>
                    <template #default>删除</template>
                  </a-button>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
      <!-- /table-container -->
      <Edit :model-form="data.modelForm" v-model:edit-visible="editVisible" :set-edit-visible="setEditVisible" :create-data="createData" :update-data="updateData" :dialog-status="dialogStatus" />
    </div>
  </a-card>
</template>
<style lang="scss"></style>
